/**
 * @file 封装请求模块
 */
import axios from 'axios'
import URLS from './url.map'
import qs from 'query-string'
// 可以引入store
// import store from '../../store'

const merge = (target, source) => {
  for (let key in source) {
    if (source.hasOwnProperty(key)) {
      target[key] = source[key]
    }
  }
  return target
}

class API {
  _api (options) {
    if (options.api) {
      options.url = URLS[options.api]
    }
    if (options.loading) {
      // do sth. with store
    }
    if (options.rest) {
      options.url += options.rest
    }
    return new Promise((resolve, reject) => {
      axios(options).then(res => {
        this.injectResolve(resolve, res.data)
        throw Error('FETCH_FINALLY')
      }, err => {
        this.injectReject(reject, err)
        throw Error('FETCH_FINALLY')
      }).catch(e => {
        // do sth. with store
      })
    })
  }
  injectResolve (resolve, data) {
    resolve(data)
    // do sth. with store
  }
  injectReject (reject, data) {
    reject(data)
  }
  get (api, params, options = {}) {
    merge(options, {
      api,
      params,
      method: 'GET'
    })
    return this._api(options)
  }
  post (api, data, options = {}) {
    if (options.headers && options.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      data = qs.stringify(data)
    }
    merge(options, {
      api,
      data,
      method: 'POST'
    })
    return this._api(options)
  }
}

const base = new API()

export default base
